import { Hono } from 'hono';
import { HonoContext } from './types/hono';
import { AppError } from './utils/error';
import { ReturnResponse } from './utils/response';

// Import routes
import novelRoutes from './routes/novel';
import authRoutes from './routes/auth';
import oauthRoutes from './routes/oauth';
import { validateToken } from './handlers/auth';

const app = new Hono();

// CORS middleware
app.use("*", async (c: HonoContext, next) => {
    const origin = c.req.header("Origin");
    const allowedOrigins = c.env.ALLOWED_ORIGINS.split(',');

    if (origin && allowedOrigins.includes(origin)) {
        c.res.headers.set("Access-Control-Allow-Origin", origin);
        c.res.headers.set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        c.res.headers.set("Access-Control-Allow-Headers", "Content-Type, Authorization");
    }

    return next();
});

// 根据token获取用户信息
app.use('*', async (c:HonoContext, next)=>{
    const authHeader = c.req.header('Authorization');
    if (!authHeader) {
        return next();
    }

    const [scheme, token] = authHeader.split(' ');
    if (scheme !== 'Bearer' || !token) {
        return next();
    }

    const user = await validateToken(c, token);
    if (!user) {
        return next();
    }

    // 将用户信息存储到上下文中
    c.set('user', user);
});

// Error handling
app.onError((err, c) => {
    console.error(err);

    if (err instanceof AppError) {
        return c.json(ReturnResponse.error(err.code, err.message));
    }
    return c.json(err.message, 500);
});

// Routes
app.route('/api/novels', novelRoutes);
app.route('/api/auth', authRoutes);
app.route('/api/oauth', oauthRoutes);

export default app;
